<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input id="text" type="text"/>
<button onclick="sendMessage()">Send</button>
<button onclick="closeWebSocket()">Close</button>
<div id="message"></div>
</body>
</html>
<script type="application/javascript">
    var websocket = null;

    var urlPath = window.document.location.href;  //浏览器显示地址 http://10.15.5.83:5555/ISV/demo.aspx?a=1&b=2
    var docPath = window.document.location.pathname; //文件在服务器相对地址 /ISV/demo.aspx
    var index = urlPath.indexOf(docPath);
    var serverHost = urlPath.substring(0, index);

    // 判断浏览器是否支持 WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket(serverHost.replace("http", "ws") + "/user/ws/user");
    } else {
        alert("您的浏览器不支持WebSocket");
        window.close();
    }

    /**
     * 链接发生错误
     */
    websocket.onerror = () => {
        setMessageInnerHTML("<p>error</p>");
    }

    /**
     * WebSocket链接成功
     */
    websocket.onopen = (event) => {
        setMessageInnerHTML("WebSocket 链接成功");
    }

    /**
     * 收到服务器发送过来的消息
     */
    websocket.onmessage = (event) => {
        setMessageInnerHTML("<p>" + event.data + "</p>");
    }

    /**
     * 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
     */
    websocket.onclose = () => {
        websocket.close();
    }

    /**
     * 将消息显示在网页上
     * @param innerHTML 需要显示在网页上的参数
     */
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML;
    }

    /**
     * 关闭链接
     */
    function closeWebSocket() {
        websocket.close();
    }

    /**
     * 发送消息
     */
    function sendMessage() {
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>